<!--
 * @Author: doing
 * @Date: 2023-09-16 19:41:47
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-17 11:12:24
 * @FilePath: \水果新鲜识别项目\web-admin\src\pages\role\components\AssignMenu.vue
 * @Description: 
 * 分配角色菜单
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
-->
<template>
  <el-drawer v-model="showDrawer" :title="title" size="30%" :destroy-on-close="destroyOnClose" @close="clean">
    <div class="formDrawer">
      <div class="body">
        <el-tree-v2 ref="elTreeRef" node-key="id" :check-strictly="checkStrictly"
          :default-expanded-keys="defaultExpandedKeys" :data="ruleList" :props="{ label: 'title', children: 'children' }"
          show-checkbox :height="treeHeight" @check="handleTreeCheck" v-loading="isMenuTreeLoading">
          <template #default="{ node, data }">
            <div class="flex items-center">
              <el-tag :type="type(data)">{{ typeText(data) }}</el-tag>
              <span class="ml-2 text-sm"> {{ data.title }} </span>
            </div>
          </template>
        </el-tree-v2>
      </div>
      <div class="actions">
        <el-button type="primary" @click="submit" :loading="loading">确定</el-button>
        <el-button type="default" @click="close">取消</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import { ref, computed, toRef, nextTick } from "vue"
import Menu from '~/api/menu.js'
import Role from '~/api/role.js'
import {
  toast,
  getAllMenuIds
} from '~/composables/util.js'

const showDrawer = ref(false)
const loading = ref(false)
const props = defineProps({
  destroyOnClose: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '分配权限'
  },
  data: {
    type: Object,
    default: () => ({})
  }
})
// 关闭
const close = () => showDrawer.value = false

// 提交
const emit = defineEmits(["clean"])
const clean = () => {
  //其他事情
  emit("clean")
}

// 向父组件暴露以下方法
defineExpose({
  open,
  close
})

const isMenuTreeLoading = ref(false)
const assignMenuRef = ref(null)
const menuids = ref([])
const targetmenuids = ref([])

const elTreeRef = ref(null)
const checkStrictly = ref(false)
const ruleList = ref([])
const treeHeight = ref(0)
const roleId = ref(0)
//造一个假数据,防止数据延迟
const defaultExpandedKeys = ref([])
const typeText = computed(() => {
  return function (res) {
    if (res.type === 0) {
      return '目录'
    } else if (res.type === 1) {
      return '菜单'
    } else {
      return '按钮'
    }
  }
})
const type = computed(() => {
  return function (res) {
    if (res.type === 1) {
      return 'success'
    } else if (res.type === 2) {
      return 'warning'
    } else {
      return 'info'
    }

  }
})


async function open() {
  //打开
  loading.value = false
  showDrawer.value = true
  //开始加载样式
  isMenuTreeLoading.value = true


  //获取到所有的菜单权限
  await Menu.getMenuTree().then(async (res) => {
    //设置初始值
    ruleList.value = res.data.data
    console.log('菜单权限列表')
    console.log(ruleList.value)
  }).catch(err => {
    console.log(err)
  })

  
  await nextTick(() => {
    roleId.value = toRef(props.data).value.id
    treeHeight.value = window.innerHeight - 180
    checkStrictly.value = true
    //默认展开的节点，这里只有根节点
    defaultExpandedKeys.value = getAllMenuIds(ruleList.value)
    console.log('默认展开的节点')
    console.log(defaultExpandedKeys.value)
  })

  //根据id获取到当前角色所有的菜单权限(数组)
  await Menu.getMenuIdByRole(roleId.value).then(async (res) => {
    console.log(res)
    menuids.value = res.data.data
    await setTimeout(() => {
      //将数组中的id值和对对应的checked设置为true
      elTreeRef.value.setCheckedKeys(menuids.value, true)
      console.log('当前角色所拥有的菜单权限集合')
      console.log(menuids.value)
      targetmenuids.value = [...menuids.value]
      checkStrictly.value = false
    }, 150);
  })

  isMenuTreeLoading.value = false
}

//监听
const handleTreeCheck = (...e) => {
  const { checkedKeys, halfCheckedKeys } = e[1]
  targetmenuids.value = checkedKeys.concat(halfCheckedKeys)
  console.log(targetmenuids.value)
}



//提交
const submit = async function () {
  console.log('角色id为' + '\t' + roleId.value)
  console.log('提交数据为')
  let data = {
    roleId: roleId.value,
    menuIds: targetmenuids.value
  }
  console.log(data)
  loading.value = true
  await Role.updateRoleMenu(data).then(res => {
    console.log(res)
    if (res.data.data !== null) {
      toast('更新成功', 'success', false, 3000)
    } else {
      toast(res.data.msg, 'warning', false, 3000)
    }
    close()
    loading.value = false
  }).catch(err => {
    console.log(err)
  })
}



</script>
<style>
.formDrawer {
  width: 100%;
  height: 100%;
  position: relative;
  @apply flex flex-col;
}

.formDrawer .body {
  flex: 1;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 50px;
  overflow-y: auto;
}

.formDrawer .actions {
  height: 50px;
  @apply mt-auto flex items-center;
}
</style>